import * as utils from '../utils'

function createCourse03 (gl: WebGLRenderingContext, dom: HTMLCanvasElement) {
  gl.clearColor(0.0, 0.0, 0.0, 1.0)
  gl.clear(gl.COLOR_BUFFER_BIT)
  const vectexShaderSrc = `
    attribute vec4 a_Position;
      void main() {
          gl_Position = a_Position;
          gl_PointSize = 10.0;
      }
    `

  const fragmentShaderSrc = `
      void main() {
          gl_FragColor  = vec4(1.0, 0.0, 0.0, 1.0);
      }
    `
  const program = utils.initShaders(gl, vectexShaderSrc, fragmentShaderSrc)

  const aPosition = gl.getAttribLocation(program, 'a_Position')

  const aPoints: [number, number][] = []
  dom.addEventListener('click', function (event: MouseEvent) {
    gl.clearColor(0.0, 0.0, 0.0, 1.0)
    gl.clear(gl.COLOR_BUFFER_BIT)
    const { clientX, clientY } = event
    const { width, height, offsetLeft, offsetTop } = dom
    const x = (clientX - offsetLeft) / width * 2 - 1
    const y = -(clientY - offsetTop) / height * 2 + 1
    aPoints.push([x, y])

    for (let i = 0; i < aPoints.length; i++) {
      const [x, y] = aPoints[i]
      gl.vertexAttrib3f(aPosition, x, y, 0.0)
      gl.drawArrays(gl.POINTS, 0, 1)
    }
  })
}

export {
  createCourse03
}
